package com.pcbly.web.components.email;
  
import java.util.ArrayList;  
import java.util.List;  
 
import javax.mail.Folder;
import javax.mail.Message;  
import javax.mail.Part; 
import javax.mail.Store;    
 
import com.pcbly.web.Constants;
import com.pcbly.web.bean.mail.UserMailBean;  
import com.pcbly.web.bean.mail.UserReceiveMainBean;

public class MailReceive extends AbstractReceive  {
	public MailReceive() {

	}  
	private String userId;
	
	public String getUserId() {
		return userId;
	}


	public void setUserId(String userId) {
		this.userId = userId;
	}


	public List<UserReceiveMainBean> receiveMail() {
		List<UserReceiveMainBean> list = new ArrayList<UserReceiveMainBean>();
		try {
			Store store = getStore();
			if (store.isConnected()) {
				Folder folder = store.getFolder("INBOX");
				if (folder.exists()) {
					folder.open(Folder.READ_ONLY); 
					Message[] messages = folder.getMessages(); 
					for (Message message : messages) { 
						log.debug("==========================start======================================");
						UserReceiveMainBean mainBean = new UserReceiveMainBean();
						mainBean.setTitle(getSubject(message));  
//						mainBean.setFlag(Constants.EMAIL_FLAG_BOX_RECIEVE); 
						mainBean.setReadFlag(Constants.EMAIL_NOTREAD_FLAG);
						mainBean.setUserMailId(bean.getId());
						mainBean.setFroms(getFrom(message));
						mainBean.setUserId(userId);
						setToOrCC(mainBean,message);
						mainBean.setReceiveDate(getSentDate(message));
						mainBean.setContent(getMailContent((Part) message)); 
						if (isContainAttach((Part) message)) {
							mainBean.setIsAttach(1);
							mainBean.setAttachPath(saveAttachMent((Part) message));
						} else {
							mainBean.setIsAttach(0);
						}
						list.add(mainBean); 
						log.debug("==============================end==================================");
//						break;
					}
				}
				if(folder!=null){
					folder.close(true);
				}
			}
			if(store!=null){
				store.close();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return list; 
	}
 
	
	public static void main(String[] args){
		MailReceive receive=new MailReceive();
		UserMailBean bean=new UserMailBean();
		bean.setPopSSL("1"); 
		bean.setPopPort(995);
		bean.setUserName("pxjianke@hotmail.com");
		bean.setPopHostName("pop3.live.com");
		bean.setPassword("tsgm23258759");
		
		receive.setBean(bean);
		receive.receiveMail();
		
		
		
	}
}
